package com.example.program.Aop;

import com.alibaba.fastjson.JSONObject;
import com.example.program.mapper.OperateLogMapper;


import com.example.program.pojo.OperateLog;
import com.example.program.utils.JWT;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect //当前类为切面类
@Slf4j
public class timeAOP {
@Autowired
private HttpServletRequest request;
@Autowired
   private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.example.program.anno.LOg)")
    public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {
//获取令牌中的id
        String jwt=request.getHeader("token");
        Claims claims= JWT.parseJWT(jwt);
        Integer operateUser=(Integer) claims.get("id");
//操作时间
        LocalDateTime operateTime=LocalDateTime.now();
//操作类名
        String className=pjp.getTarget().getClass().getName();
        //操作方法名
        String methodName=pjp.getSignature().getName();
        //操作方法参数
        Object[] args=pjp.getArgs();
        String methodParams= Arrays.toString(args);
        //调用原始方法
        long begin = System.currentTimeMillis();
        Object result=pjp.proceed();
        long end = System.currentTimeMillis();
        //返回值
        String returnValue= JSONObject.toJSONString(result);
//耗时
        Long cost=end-begin;

        //操作日志
        OperateLog operateLog=new  OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,cost);
operateLogMapper.insert(operateLog);
return result;

    }
}
